﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.Xml;

namespace IVTQLBH.UTILITIES
{
    public class TrackingUtility
    {
        /// <summary>
        /// Get the location from IP Address using the free 
        /// services of (http://freegeoip.appspot.com/xml/) 
        /// Created: 28 Feb 2010
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <returns> The Response into the Datatable Index 0 </returns>

        public static DataTable GetLocation(string ipaddress)
        {
            string url = "http://api.ipinfodb.com/v2/ip_query.php?key={0}&ip={1}&timezone=true";

            url = String.Format(url, "db82107efe43af68c15c698dade9eadb9c3ff618c991cde5d0a72f7d78db6668", ipaddress);

            HttpWebRequest httpWRequest = (HttpWebRequest)WebRequest.Create(url);
            using (HttpWebResponse httpWResponse = (HttpWebResponse)httpWRequest.GetResponse())
            {

                XmlTextReader xtr = new XmlTextReader(httpWResponse.GetResponseStream());
                DataSet ds = new DataSet();
                ds.ReadXml(xtr);
                return ds.Tables[0];
            }

        }

        public static DataTable GetLocation1(string strIPAddress)
        {
            //Create a WebRequest with the current Ip
            WebRequest _objWebRequest =
                WebRequest.Create("http://freegeoip.appspot.com/xml/" //http://ipinfodb.com/ip_query.php?ip=
                               + strIPAddress);
            //Create a Web Proxy
            WebProxy _objWebProxy =
               new WebProxy("http://freegeoip.appspot.com/xml/"
                         + strIPAddress, true);

            //Assign the proxy to the WebRequest
            _objWebRequest.Proxy = _objWebProxy;

            //Set the timeout in Seconds for the WebRequest
            _objWebRequest.Timeout = 2000;

            try
            {
                //Get the WebResponse 
                WebResponse _objWebResponse = _objWebRequest.GetResponse();
                //Read the Response in a XMLTextReader
                XmlTextReader _objXmlTextReader
                    = new XmlTextReader(_objWebResponse.GetResponseStream());

                //Create a new DataSet
                DataSet _objDataSet = new DataSet();
                //Read the Response into the DataSet
                _objDataSet.ReadXml(_objXmlTextReader);

                return _objDataSet.Tables[0];
            }
            catch
            {
                return null;
            }

        } // End of GetLocation


    }
}
